from flask import jsonify, make_response, request, g
from flask_jwt_extended import get_jwt_identity
from flask_restful import Resource
from sqlalchemy.orm import aliased

from apps.model.serializeModel import model_to_list, model_to_dict
from apps.settingApi.switchCase.casePrimaryKey import caseGetPrimaryKeyData
from apps.settingApi.switchCase.serializeParameter import serializeGetFilter, pageResultData, getArgsData, \
    serializeParData

from apps.settingApi.switchCase.settingCurd import getPk, deletePk, putPk
from apps.settingApi.api.funs.model import funsModel
from apps.settingApi.utils import getDataTime
from comm.sqlalchemyConfig import db
from comm.decorator import login_required

funsViewModel = funsModel

class lesseesValidListView(Resource):
    @login_required()
    def get(self):
        dataList = []
        # 格式化获取当前时间
        formatted_datetime = getDataTime()
        modelData = db.session.query(funsViewModel.code,funsViewModel.name).filter(funsViewModel.status==1).all()
        for itm in modelData:
            dataList.append({
                "code":itm.code,
                "name":itm.name
            })
        return make_response(jsonify({'msg': 'ok', 'result': dataList}), 200)


# 字典操作=========================================================
class funsListView(Resource):
    # 查询用户列表
    @login_required()
    def get(self):
        # 获取所有的参数
        serializeFilterList, args = serializeGetFilter(funsViewModel)
        result = funsViewModel.getTreeAll(serializeFilterList)
        objData = {}
        objData["data"] = result
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

    @login_required()
    def post(self):
        # 获取参数
        args,err = getArgsData()
        if err!=None:
            return make_response(jsonify({'msg': err}), 202)
        id_z = caseGetPrimaryKeyData()
        args['create_user'] = g.user_id
        args['id'] = id_z
        # 序列化跟校验参数
        addData, err = serializeParData(model=funsViewModel, argsData=args)
        if err != None:
            return make_response(jsonify({'msg': err}), 202)
        # 判断名称是否重复
        exit_z = db.session.query(funsViewModel).filter_by(code=args['code']).first()
        if exit_z != None:
            return make_response(jsonify({'msg': 'code重复'}), 202)
        result = db.session.query(funsViewModel).with_for_update().filter_by(id=id_z).first()
        # 如果数据不存在，则添加新数据
        if result != None:
            db.session.commit()
            return make_response(jsonify({'msg': '抢先操作重新提交试试'}), 202)
        try:
            add = funsViewModel(**addData)
            db.session.add(add)
            db.session.commit()
            db.session.flush()
            objData = model_to_dict(add, [])
        except Exception as e:
            return make_response(jsonify({'msg': '新增失败' + repr(e)}), 202)

        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)


class funsPkView(Resource):
    @login_required()
    def get(self, pk):
        objData, err = getPk(funsViewModel, pk)
        if err != None:
            return make_response(jsonify({'msg': err}), 202)
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

    @login_required()
    def put(self, pk):
        # 获取所有参数
        args, err = getArgsData()
        if err != None:
            return make_response(jsonify({'msg': err, }), 202)
        if 'code' in args.keys():
            del args['code']
        objData, err = putPk(funsViewModel, pk, args)
        if err != None:
            return make_response(jsonify({'msg': err}), 202)
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

    @login_required()
    def delete(self, pk):
        objData, err = deletePk(funsViewModel, pk)
        if err != None:
            return make_response(jsonify({'msg': err}), 202)
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)